clc; clearvars; close all;
addpath('CEC2010\')
addpath('CEC2010\datafiles\');
addpath('CEC2010\javarandom\bin\');
addpath('CEC2010\javarandom\src\');
global initial_flag

NS = 50;   % 种群数
dim = 1000;   % 种群维度
s = 20;   % 子控件数目
upperBound = [100, 5, 32, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 100];
lowerBound = [-100, -5, -32, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -100];
bestYhistory = [];    % 保存每次迭代的最佳值
bestfit1history = [];
bestfit2history = [];
% sList = [5, 10, 25, 50, 100, 200];   % 组大小池
% sHistory = [];

for funcNum = 4

    initial_flag = 0;    % 换一个函数initial_flag重置为0
    sampleX = lhsdesign(NS, dim).*(upperBound(funcNum) - lowerBound(funcNum)) + lowerBound(funcNum).*ones(NS, dim);    % 生成NS个种群,并获得其评估值
    lastSampleX = sampleX;
    [sampleY, fit1, fit2] = Copy_of_benchmark_func(sampleX, funcNum);
    [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
    bestX = sampleX(bestIndex, :);
    bestYhistory = [bestYhistory; bestY];
    bestfit1history = [bestfit1history; fit1(bestIndex)];
    bestfit2history = [bestfit2history; fit2(bestIndex)];
    for i0 = 1 : 100     % 迭代50次
        
        % s = sList(randi(5));     % 子空间的数目
        % sHistory = [sHistory; s];
        if i0 == 1
            delta = zeros(1, dim);
            [~, index] = sort(delta);
        end

        for i1 = 1 : s
            index1 = index(((i1 - 1) * (dim / s) + 1) : (i1 * (dim / s)));
            subX = sampleX(:, index1);
            subX = SaNSDE(subX, sampleY, bestX, index1, 50, dim / s, lowerBound(funcNum), upperBound(funcNum), @(x)benchmark_func(x, funcNum));% 100*400
            sampleX(:, index1) = subX;
            [sampleY, fit1, fit2] = Copy_of_benchmark_func(sampleX, funcNum);   % 100
            [bestY, bestIndex] = min(sampleY);    % 获取全局最小值以及对应的种群
            bestX = sampleX(bestIndex, :);
        end

        bestYhistory = [bestYhistory; bestY];
        bestfit1history = [bestfit1history; fit1(bestIndex)];
        bestfit2history = [bestfit2history; fit2(bestIndex)];
        delta = sum(abs(sampleX - lastSampleX),1) ./ NS;
        % delta = sum(sampleX - lastSampleX,1) ./ NS;
        [~, index] = sort(delta);
        lastSampleX = sampleX;
        disp(i0);
    end
end
figure(1);
plot(bestYhistory);
hold on;
plot(bestfit1history);
hold on;
plot(bestfit2history);
save('DECC_DY.mat','bestYhistory');
save('DECC_Dfit1.mat','bestfit1history');
save('DECC_Dfit2.mat','bestfit2history');
legend('Y','fit1','fit2','Location', 'northeast');